﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Vision001.Helper
{
    /// <summary>
    /// 文件写入帮助类
    /// </summary>
    public static class FileWriteHelper
    {
        private static string AllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "测试报告");

        public static void WriteToFile<T>(List<T> list, string delimiter = "     ")
        {
            try
            {
                if (list == null || list.Count == 0)
                    return;

                FileIsExit();
                string time1 = DateTime.Now.ToString("yyyy-MM-dd");
                string time2 = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
                string filePath = Path.Combine(AllPath, time1, time2 + ".txt");
                if (!File.Exists(filePath))
                {
                    File.Create(filePath).Close();
                }
                var type = typeof(T);
                var properties = type.GetProperties();
                using (var fileStream =
                       new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 65536))
                {
                    var writer = new StreamWriter(fileStream, Encoding.UTF8, 65536);
                    for (int i = 0; i < properties.Length; i++)
                    {
                        writer.Write(properties[i].Name);
                        if (i < properties.Length - 1)
                            writer.Write(delimiter);
                    }
                    writer.WriteLine();

                    // 批量写入数据行
                    foreach (var item in list)
                    {
                        for (int i = 0; i < properties.Length; i++)
                        {
                            var value = properties[i].GetValue(item)?.ToString() ?? string.Empty;

                            // 快速写入，避免不必要的字符串处理
                            if (NeedEscape(value, delimiter))
                            {
                                writer.Write('"');
                                writer.Write(value.Replace("\"", "\"\""));
                                writer.Write('"');
                            }
                            else
                            {
                                writer.Write(value);
                            }

                            if (i < properties.Length - 1)
                                writer.Write(delimiter);
                        }

                        writer.WriteLine();
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        private static bool NeedEscape(string value, string delimiter)
        {
            return !string.IsNullOrEmpty(value) &&
                   (value.Contains(delimiter) || value.Contains("\"") ||
                    value.Contains("\n") || value.Contains("\r"));
        }

        public static void FileIsExit()
        {
            // 确保目录存在

            if (!string.IsNullOrEmpty(AllPath) && !Directory.Exists(AllPath))
            {
                Directory.CreateDirectory(AllPath);
            }

            string path = Path.Combine(AllPath, DateTime.Now.ToString("yyyy-MM-dd"));
            if (!string.IsNullOrEmpty(path) && !Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }
    }
}